/* Copyright 2012 The Go Authors.  All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
'use strict';

/* Controllers */


angular.module('tour.controllers', []).

  // Navigation controller
  controller('NavCtrl',
  	['$scope', 'Nav', function($scope, Nav) {

  	Nav(function(nav) {
  		$scope.pages = nav.module.Pages;
	  	$scope.nextPage = nav.next;
	  	$scope.prevPage = nav.prev;
	  	$scope.gotoPage = nav.goto;
	  	$scope.currentPage = nav.current;
	  	$scope.moduleName = nav.module.Title;
	});

  }]).

  // Module controller
  controller('ModuleCtrl', ['$scope', 'I18n', 'Fmt', 'Run', 'Nav',
  	function($scope, I18n, Fmt, Run, Nav) {

  	var openPage = function(page) {
  		// Save the output before leaving the page.
  		$(".output").each(function(idx, elm) {
			$scope.page.Files[idx].Output = $(elm).html();
  		});

  		$scope.page = page;
	  	$scope.openFile = function(f) {
	  		$scope.file = f;
	  	}
	  	$scope.openFile(page.Files && page.Files[0]);
  	};

	Nav(function(nav) { nav.onPageChange(openPage); });

  	// wrapper function logging 'waiting' message on the output panel.
  	function remote(f) {
  		return function() {
	  		$(".output.active").html('<pre class="info">'+I18n.L('waiting')+'</pre>');
	  		f();
	  	}
  	}

  	$scope.run = remote(function() {
  		Run($scope.file.Content, $(".output.active > pre")[0]);
	});
	window.run = $scope.run;

	$scope.format = remote(function() {
		Fmt($scope.file.Content,
			function(error) {
  				$(".output.active").html('<pre class="stderr">'+error+'</p>');
			},
			function(code) {
  				$(".output.active").html('');
				$scope.file.Content = code;
			});
	})
  }]);